/**
 * Copyright 2019 Inc.
 **/
package com.myz.rabbitmqspring.spring.config;

import com.myz.rabbitmqspring.spring.listen.ConfirmCallbackListener;
import com.myz.rabbitmqspring.spring.listen.ReturnCallbackListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author maoyz0621 on 19-4-16
 * @version: v1.0
 */
@Configuration
public class RabbitConfig {

    private static final Logger logger = LoggerFactory.getLogger(RabbitConfig.class);

    @Resource
    private ConnectionFactory connectionFactory;

    @Bean
    public RabbitTemplate.ConfirmCallback confirmCallbackListener(){
        return new ConfirmCallbackListener();
    }

    @Bean
    public RabbitTemplate.ReturnCallback returnCallbackListener(){
        return new ReturnCallbackListener();
    }

    /**
     * 创建RabbitTemplate
     *
     * @return
     */
    @Bean
    public RabbitTemplate rabbitTemplate() {
        logger.debug("************** generate RabbitTemplate ******************");

        // 创建RabbitTemplate
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        rabbitTemplate.setConfirmCallback(new ConfirmCallbackListener());
        rabbitTemplate.setReturnCallback(new ReturnCallbackListener());
        return rabbitTemplate;
    }
}
